<?php
/* This file is part of LlamaSlayers Ajax Chat
 *
 * The source code is released under the GNU GPL free software license, version 3.
 * Updates can be found at http://llamaslayers-ajax-chat.googlecode.com/
 */

require_once dirname( __FILE__ ) . '/config.php';

session_start();

$_GET['_room'] = empty( $_GET['room'] ) ? null : $_GET['room'];

if ( empty( $_GET['room'] ) || !trim( $_GET['room'] ) )
	$_GET['room'] = 'public';

$_GET['room'] = preg_replace( '/[^a-z0-9_\-]/', '', strtolower( trim( $_GET['room'] ) ) );

if ( $_GET['room'] != $_GET['_room'] ) {
	header( 'Location: ' . CHAT_HOME . 'chat.php?room=' . $_GET['room'] . ( empty( $_SESSION['name'] ) && !empty( $_GET['name'] ) ? '&name=' . $_GET['name'] : '' ) );
	exit;
}

if ( empty( $_SESSION['name'] ) && !( empty( $_COOKIE ) && !empty( $_GET['name'] ) && trim( $_GET['name'] ) ) ) { ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> 
	<title>Chat</title>
	<style type="text/css">
		h1 {
			font-weight: normal;
			font-family: Impact, sans-serif;
		}
	</style>
</head>
<body>
	<h1>What is your name?</h1>
	<form action="name-noscript.php" method="get"><input id="name" name="name" type="text"/></form>
</body>
</html>
<?php
	exit;
}

if ( empty( $_SESSION['name'] ) && !empty( $_GET['name'] ) )
	$_SESSION['name'] = $_GET['name'];

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> 
	<title>Chat (<?php echo $_GET['room']; ?>)</title>
<?php if ( isset( $_GET['inner'] ) ) { ?>
	<meta http-equiv="refresh" content="15"/>
<?php } ?>
	<style type="text/css">
		h1,h2 {
			font-weight: normal;
			font-family: Impact, sans-serif;
		}
		h2 {
			margin-top: 0;
		}
		#right {
			float: right;
			width: 25%;
			clear: right;
		}
		input {
			width: 100%;
		}
		.alt {
			background-color: #f7f7f7;
		}
		#chat {
			width: 75%;
		}
		#chat, table {
			background-color: #fff;
			font-family: sans-serif;
		}
		table {
			width: 100%;
			outline: 1px solid #333;
			border-collapse: collapse;
		}
		thead th {
			background-color: #555;
			color: #fff;
			border: 1px solid #ddd;
		}
		tbody th {
			text-align: left;
			border: 1px solid #ccc;
		}
		tbody td {
			border: 1px solid #ccc;
		}
		#chat div .time {
			float: right;
			font-size: smaller;
			margin: 2px;
			display: block;
		}
	</style>
</head>
<body>
<?php if ( isset( $_GET['inner'] ) ) { ?>
	<div id="right">
		<div id="online"><h2>Users online</h2><?php

if ( !file_exists( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' ) )
	touch( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' );

$online = (array)file( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt' );

foreach ( $online as $id => $on ) {
	if ( (int)substr( $on, 32 ) < time() - 75 )
		unset( $online[$id] );
	if ( substr( $on, 0, 32 ) == md5( $_SERVER['HTTP_USER_AGENT'] . '@' . $_SERVER['REMOTE_ADDR'] ) )
		unset( $online[$id] );
}

$online[] = md5( $_SERVER['HTTP_USER_AGENT'] . '@' . $_SERVER['REMOTE_ADDR'] ) . time() . ':' . urlencode( $_SESSION['name'] );
sort( $online );
file_put_contents( dirname( __FILE__ ) . '/db/online/' . $_GET['room'] . '.txt', implode( "\n", array_map( 'trim', $online ) ) );

foreach ( $online as $on ) {
	$split = explode( ':', $on );
	if ( substr( $on, 0, 1 ) == '*' )
		echo '<img src="icons/' . $split[2] . '_large.png" width="48" height="48" title="' . htmlspecialchars( urldecode( $split[1] ) ) . '" alt="' . htmlspecialchars( urldecode( $split[1] ) ) . '"/>';
	else
		echo '<img src="http://gravatar.com/avatar/' . substr( $on, 1, 32 ) . '?d=identicon&s=48&amp;r=d" width="48" height="48" title="' . htmlspecialchars( urldecode( substr( $on, strpos( $on, ':' ) + 1 ) ) ) . '" alt="' . htmlspecialchars( urldecode( substr( $on, strpos( $on, ':' ) + 1 ) ) ) . '"/>';
}

?></div>
		<div id="channels"><h2>Other channels</h2><table><thead><tr><th scope="col">Name</th><th scope="col">Last message</th><th scope="col">Last viewed</th><th scope="col">Users</th></tr></thead><tbody><?php

function plural( $num ) {
	if ( $num != 1 )
		return 's';
}

function time_since( $date ) {
	$diff = time() - $date;
	if ( $diff == 0 )
		return 'Right now';
	if ( $diff < 60 )
		return $diff . ' second' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 60 );
	if ( $diff < 60 )
		return $diff . ' minute' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 60 );
	if ( $diff < 24 )
		return $diff . ' hour' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 24 );
	if ( $diff < 7 )
		return $diff . ' day' . plural( $diff ) . ' ago';
	$diff = floor( $diff / 7 );
	if ( $diff < 4 )
		return $diff . ' week' . plural( $diff ) . ' ago';
	return 'on ' . date( 'F j<\\s\\u\\p>S</\\s\\u\\p>, Y', $date );
}

function clean_online_list( $room ) {
	$_members = file( dirname( __FILE__ ) . '/db/online/' . $room );
	$_members = array_filter( array_map( 'trim', $_members ) ); // Remove blank lines
	$members = array();
	foreach ( $_members as $member ) {
		if ( (int)substr( $member, 33 ) >= time() - 75 )
			$members[] = $member;
	}
	if ( $_members != $members )
		file_put_contents( dirname( __FILE__ ) . '/db/online/' . $room, implode( "\n", $members ) );
	return $members;
}

$_channels = glob( dirname( __FILE__ ) . '/db/chat/*.txt' );
$channels = array();

foreach ( $_channels as $channel ) {
	$channels[filesize( $channel ) > 1 ? filemtime( $channel ) : 0][] = array( substr( basename( $channel ), 0, -4 ), fileatime( $channel ), count( clean_online_list( basename( $channel ) ) ) );
}

krsort( $channels, SORT_NUMERIC );

$alt = false;

$i = 5;

foreach ( $channels as $mtime => $_channel ) {
	foreach ( $_channel as $channel ) {
		if ( $_GET['room'] == $channel[0] || $i-- < 0 )
			continue;
		echo '<tr' . ( $alt ? ' class="alt"' : '' ) . '><th scope="row">#<a href="chat.php?room="' . $channel[0] . '">' . $channel[0] . '</a></th><td>' . ( $mtime ? time_since( $mtime ) : 'Never' ) . '</td><td>' . time_since( $channel[1] ) . '</td><td>' . number_format( $channel[2] ) . '</td></tr>';
		$alt = !$alt;
	}
}

?></tbody></table></div>
	</div>
	<h1>Chat (<?php echo $_GET['room']; ?>)</h1>
	<div id="chat"><?php

if ( !file_exists( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ) )
	touch( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' );

$chat = array_slice( file( dirname( __FILE__ ) . '/db/chat/' . $_GET['room'] . '.txt' ), -25 );

$alt = false;

foreach ( $chat as $message ) {
	if ( !strlen( trim( $message ) ) ) // Avoid blank lines
		continue;
	$_message = explode( ':', $message );
	echo '<div' . ( $alt ? ' class="alt"' : '' )  . ( strpos( $message, ':Global:' ) ? ' style="fontSize: 1.25em"' : '' ) . '><span class="time">' . time_since( $_message[1] ) . '</span>';

	if ( substr( $message, 0, 1 ) == '*' )
		echo '<img src="icons/' . ltrim( substr( $message, 1, 31 ), '*' ) . '_small.png" width="15" height="15"/>';
	else
		echo '<img src="http://gravatar.com/avatar/' . substr( $message, 0, 32 ) . '?d=identicon&s=15&amp;r=d" width="15" height="15"/>';

	echo ' <strong>' . htmlspecialchars( urldecode( substr( $_message[0], 32 ) ) ) . ':</strong> ' . preg_replace( '/(ht|f)tps?:\/\/((\w+)(:(\w+))?@)?([a-zA-Z0-9\-.]+|\[[a-zA-Z0-9\-.]+\])\.?(:(\d+))?(\/\S*)?/', '<a href="\\0" target="_blank">\\0</a>', preg_replace( '/(^|\\s)#([a-zA-Z0-9\-_]+)/', '\\1#<a href="chat.php?room=\\2">\\2</a>', htmlspecialchars( urldecode( implode( ':', array_slice( $_message, 2 ) ) ) ) ) ) . '</div>';
	$alt = !$alt;
}

?></div>
<?php } else { ?>
	<iframe src="chat.php?room=<?php echo $_GET['room'] . '&amp;name=' . urlencode( $_GET['name'] ) . '&amp;inner'; ?>" style="border:0" height="600" width="100%"></iframe>
	<form action="send-noscript.php" method="get"><input id="message" name="message" type="text"/><input type="hidden" id="room" name="room" value="<?php echo $_GET['room']; ?>"/><input type="hidden" id="name" name="name" value="<?php echo addslashes( $_GET['name'] ); ?>"/></form>
<?php } ?>
</body>
</html>